package com.triptogether.utils.gcm;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

import com.triptogether.utils.androidsystem.SystemUtils;
import com.triptogether.utils.log.Logger;

public class GcmSharedPreferences {

	static final String TAG = Logger.makeLogTag(GcmSharedPreferences.class);

	public static final String GCM_SHARED_PREFERENCES = "gcm_shared_preferences";
	private final static String GCM_PROPERTY_KEY_REG_ID = "property_reg_id";
	private final static String GCM_PROPERTY_KEY_APP_VERSION = "property_app_version";

	private static SharedPreferences getSharedPreferences(Context context) {
		return context.getSharedPreferences(GCM_SHARED_PREFERENCES, Context.MODE_PRIVATE);
	}

	/**
	 * Stores the registration ID and the app versionCode in the application's
	 * {@code SharedPreferences}, for future use.
	 * 
	 * @param context
	 *            application's context.
	 * @param regId
	 *            registration ID
	 */
	public static void storeRegistrationId(Context context, String regId) {

		// Get the applicatoin version
		int appVersion = SystemUtils.getAppVersion(context);

		// Save the application version and the regid for future use
		Editor edit = getSharedPreferences(context).edit();
		edit.putString(GCM_PROPERTY_KEY_REG_ID, regId);
		edit.putInt(GCM_PROPERTY_KEY_APP_VERSION, appVersion);
		edit.commit();
	}

	/**
	 * Gets the current registration ID from the {@link SharedPreferences}, if
	 * there is one. </br>
	 * if the return String is empty, the app need to register on GCM services.
	 * 
	 * @param context
	 * @return registration ID, or empty string if there is no existing
	 *         registration ID.
	 */
	public static String getRegistrationId(Context context) {

		// Get the registrationId of the device from the Shared preferences, If
		// exists
		String registrationId = getSharedPreferences(context).getString(GCM_PROPERTY_KEY_REG_ID,
		                                                                "");

		if (registrationId.isEmpty()) {
			Logger.LOGI(TAG, "Registration not found.");
			return "";
		}

		// Check if app was updated; if so, it must clear the registration ID
		// since the existing regID is not guaranteed to work with the new
		// app version.
		int registeredVersion = getSharedPreferences(context).getInt(GCM_PROPERTY_KEY_APP_VERSION,
		                                                             Integer.MIN_VALUE);
		int currentVersion = SystemUtils.getAppVersion(context);
		if (registeredVersion != currentVersion) {
			Logger.LOGI(TAG, "App version changed.");
			return "";
		}
		return registrationId;
	}
}
